#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <string.h>
#include <memory>
#include "log.hpp"
#include"thread.hpp"
using namespace std;
using namespace td;
//先设置成全局的方便函数内使用
string ip;
uint16_t port;
pthread_t id;//方便后序退出时候回收对应线程
int flag=0;//标记用户QUIT后方便终止读与收两个线程
int sd;
void Recv(){
    while(1){
    char buff[1024] = {0};
    sockaddr_in other;
    socklen_t len;
        ssize_t rm= recvfrom(sd, buff, sizeof(buff) - 1, 0, (sockaddr *)&other, &len);
        if (rm< 0)  use_log(loglevel::DEBUG) << "recvfrom failure!";
           buff[rm]=0;
        cerr<<buff<<endl;/////////////////方便后序重定向
    }
}

void Send(){
    sockaddr_in local;
    bzero(&local, sizeof(local));
    local.sin_family = AF_INET;
    local.sin_port = htons(port);
    local.sin_addr.s_addr = inet_addr(ip.c_str());
    socklen_t len = sizeof(local);
    string tip="我上线了 ";
    int so = sendto(sd, tip.c_str(), tip.size(), 0, (sockaddr *)&local, len); 
    //cout<<so<<endl;
    while (1)
    {     //cout<<"Please Enter#"<<endl;
        string mess;
        getline(cin, mess);
         
        //发送：
        int so = sendto(sd, mess.c_str(), mess.size(), 0, (sockaddr *)&local, len); // 输入型参数
        if (so < 0)  use_log(loglevel::DEBUG) << "sendto failure!";
        if(mess=="QUIT") {
            flag=1;//终止读线程
            pthread_cancel(id);
        }
    }
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        cerr << " please use: " << argv[0] << " server_ip server_port" << std::endl;
        return 1;
    }
    // 创建套接字：
     sd = socket(AF_INET, SOCK_DGRAM, 0); // 网络通信/用户数据报
    if (sd < 0)
        use_log(loglevel::DEBUG) << "socket failure!";
    use_log(loglevel::DEBUG) << "socket success!";
    // os自己认识用户端机器的ip+随机会生成端口号port自动绑定与解除;故无需bind/程序终止立刻解除故查不到状态
    ip = argv[1];           
    port = stoi(argv[2]); 
   
   //创建两个线程去执行接收和发送两个任务;

    Thread t1(Recv);
    Thread t2(Send);
    t1.start();
    t2.start();
      id=t2.Id();
      t2.join();
      if(flag==1) pthread_cancel(t1.Id());
    t1.join();
    

  
   
       
    }
